/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> arr1;
        vector<int> arr2;
        auto dfs = [&](this auto&& dfs, TreeNode* root, int which) -> void{
            if(root == nullptr) return;
            if(root->left == nullptr && root->right == nullptr)
            {
                if(which == 1) arr1.emplace_back(root->val);
                else arr2.emplace_back(root->val); 
                return;
            }
            dfs(root->left, which);
            dfs(root->right, which);
        };     

        dfs(root1, 1);
        dfs(root2, 2);

        int n = arr1.size(), m = arr2.size();
        if(n != m) return false;

        for(int i = 0; i < n; ++i)
        {
            if(arr1[i] != arr2[i]) return false; 
        }
        return true;
    }
};
